Ext.BLANK_IMAGE_URL = '../jslib/ext-3.3.1/resources/images/default/s.gif';

var header = new Ext.Panel({
	region: 'north',
	contentEl: 'header',
	border: false,
	tbar:[{
		text: '添加类别',
		handler: addBookType,
		iconCls: 'icon-add'
	}, '-', {
		text: '修改类别',
		handler: modifyBookType,
		iconCls: 'icon-modify'
	}, '-', {
		text: '删除类别',
		handler: removeBookType,
		iconCls: 'icon-delete'
	}, '-','-', {
		text: '添加书籍',
		handler: addBook,
		iconCls: 'icon-add'
	},'-', {
		text: '修改书籍',
		handler: modifyBook,
		iconCls: 'icon-modify'
	},'-', {
		text: '删除书籍',
		handler: removeBook,
		iconCls: 'icon-delete'
	},'-', {
		text: '导入书籍',
		handler: importBook,
		iconCls: 'icon-import'
	},'-', {
		text: '凡例',
		handler: modifyBookGuide,
		iconCls: ''
	}]
});

var bookTypePanel = new Ext.tree.TreePanel({
    region: 'west',
    title: '书籍类别',
    width: 200,
    autoScroll: true,
    split: true,
    dataUrl: 'book-type!getAllBookTypes.action',
    root: {id:'root', text:'全部类别', expanded: true},
    //rootVisible:false,
    selModel: new Ext.tree.DefaultSelectionModel({
    	listeners:{
    		selectionchange: function(sm, n){
    			bookMgr.reloadBooks();
    		}
    	}
    })
});

var bookListStore = new Ext.data.JsonStore({
    root: 'result',
    totalProperty: 'totalItems',
    idProperty: 'id',
    remoteSort: true,
    fields: ['name', 'author', 'source'],
    url: 'book!query.action',
    listeners:{
    	beforeload: function(){ //加载数据前设置参数（后台的分页参数与Ext有异）
    		var bookType = bookMgr.getCurBookType();
    		if (!bookType) return;
    		var typeId = (bookType != bookTypePanel.getRootNode() ? bookType.id : 0);
    		var pageSize = bookListPagingToolbar.pageSize;
    		var pageNo = this.lastOptions.params ? (this.lastOptions.params.start / pageSize + 1) : 1;
    		this.baseParams = {
    			'page.pageSize': pageSize,
    			'page.pageNo': pageNo,
    			'book.typeId': typeId,
    			'book.name': '%' + Ext.getCmp('book.name').getValue() + '%'
    		};
    	}
    }
});
var bookListPagingToolbar = new Ext.PagingToolbar({
    pageSize: 30,
    store: bookListStore,
    displayInfo: true,
    displayMsg: '总数 {2}，当前显示 {0} - {1}',
    emptyMsg: "没有找到书籍",
    items:['-', {
    	xtype: 'textfield',
    	id: 'book.name',
    	name: 'book.name',
        emptyText: '输入书名查找',
        width: 100,
        listeners: {
            specialKey :function(field,e){
                if (e.getKey() == Ext.EventObject.ENTER) {//按回车
                	bookMgr.reloadBooks();
                }
            }
        }
    },' ',{
        text: '查找',
		//tooltip: '按书名查找',
        handler: function(){bookMgr.reloadBooks();}
    },{
        text: '重置',
        handler: function(){
        	Ext.getCmp('book.name').setValue('');
        	bookMgr.reloadBooks();
        }
    }]
});
var bookListPanel = new Ext.grid.GridPanel({
    region: 'center',
    header: false,
    loadMask: true,
    store: bookListStore,
    columns: [new Ext.grid.RowNumberer({
		header : '',
		renderer : function(value,metadata,record,rowIndex){
			var start = bookListStore.lastOptions.params ? bookListStore.lastOptions.params.start : 0;
			return start + rowIndex + 1;
        },
        width : 30
	}),{
        header: '书名',
        width: 200,
        dataIndex: 'name'
    },{
        header: '作者',
        width: 200,
        dataIndex: 'author'
    },{
        header: '出处',
        dataIndex: 'source',
        width: 200
    }],
    bbar: bookListPagingToolbar,
    listeners: {
    	rowdblclick: function(grid, rowIndex, e){
    		modifyBook();
    	},
    	resize: function(){ //设置各列的宽度
    		var width = (this.getWidth() - 55) / 3;
    		if (width < 150) width = 150;
    		this.getColumnModel().setColumnWidth(1, width);
    		this.getColumnModel().setColumnWidth(2, width);
    		this.getColumnModel().setColumnWidth(3, width);
    	}
    }
});

Ext.onReady(function() {
	Ext.QuickTips.init();
	new Ext.Viewport({
	    layout: 'border',
	    items: [header, bookTypePanel, bookListPanel]
	});
	bookTypePanel.getRootNode().select();
});

/**
 * 将一些公共方法集中起来
 */
var bookMgr = {
	reloadBooks: function(){
		bookListStore.load();
	},
	//取得当前选中的类别节点
	getCurBookType: function(){
		return bookTypePanel.getSelectionModel().getSelectedNode();
	},
	//重新加载类别数据
	reloadBookType: function(ifReloadBooks){
		var self = this;
		var path = self.getCurBookType().getPath();
		bookTypePanel.getRootNode().reload(function(){
			bookTypePanel.selectPath(path);
			if (ifReloadBooks && bookTypePanel.getRootNode() == self.getCurBookType()){
				self.reloadBooks();
			}
		});
	},
	//在树形结构中添加类别节点
	addBookTypeNode: function(bookType){
		bookTypePanel.root.appendChild({id: bookType.id, text: bookType.name, leaf: true}).select();
	},
	removeTypeNode: function(node){
		node.remove();
		bookTypePanel.root.select();
	},
	getCurBookId: function(){
		var record = bookListPanel.getSelectionModel().getSelected();
		return record ? record.json.id : 0;
	},
	getCurBookIds: function(){
		var records = bookListPanel.getSelectionModel().getSelections();
		if (records.length == 0){
			return null;
		}
		var ids = [];
		for (var i = 0; i < records.length; i ++){
			ids.push(records[i].json.id);
		}
		return ids;
	}
};